import React, { useEffect } from 'react';
import { Table, Button, Tag, Modal, InputNumber, Space, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import moment from 'moment';
import { useSet } from '@/utils/hooks';
import { getActivationCodeList, generateActivationCode } from '@/services/activationCode';

const ActivationCode = () => {
  const [state, setState] = useSet({
    loading: false,
    dataSource: [],
    total: 0,
    validNum: null,
    open: false,
    pageNum: 1,
    pageSize: 10,
  });

  const { loading, dataSource, total, validNum, open, pageNum, pageSize } = state;

  // 获取白名单列表
  const getActivationCodeData = (params?: any) => {
    if (loading) return;
    setState({ loading: true });
    getActivationCodeList({
      pageNum,
      pageSize,
      ...params,
    })
      .then((res) => {
        if (res) {
          setState({
            dataSource: res.rows,
            total: res.total,
          });
        }
      })
      .catch((err) => {
        console.log(err, 'err');
      })
      .finally(() => {
        setState({ loading: false });
      });
  };

  useEffect(() => {
    getActivationCodeData();
  }, []);

  console.log(dataSource, 'dataSource');

  const columns: any = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '激活码',
      dataIndex: 'activationCode',
      key: 'activationCode',
    },
    {
      title: '激活码状态',
      dataIndex: 'codeStatus',
      key: 'codeStatus',
      render: (text: number) =>
        text === 1 ? <Tag color="success">已使用</Tag> : <Tag color="error">未使用</Tag>,
    },
    {
      title: '激活码有效期',
      dataIndex: 'codeIndate',
      key: 'codeIndate',
      render: (text: number) => text && moment(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '可用设备数',
      key: 'validDeviceNum',
      dataIndex: 'validDeviceNum',
    },
    {
      title: '状态',
      dataIndex: 'dataStatus',
      key: 'dataStatus',
      render: (text: number) =>
        text === 1 ? <Tag color="success">启用</Tag> : <Tag color="error">禁用</Tag>,
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      key: 'gmtCreate',
      render: (text: number) => text && moment(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '修改时间',
      dataIndex: 'gmtModifed',
      key: 'gmtModifed',
      render: (text: number) => text && moment(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '过期时间',
      dataIndex: 'expireTime',
      key: 'expireTime',
      render: (text: number) => text && moment(text).format('YYYY-MM-DD HH:mm:ss'),
    },
  ];

  return (
    <div>
      <div style={{ marginBottom: 12 }}>
        <Button type="primary" onClick={() => setState({ open: true })} icon={<PlusOutlined />}>
          生成激活码
        </Button>
      </div>
      <Table
        size="small"
        loading={loading}
        columns={columns}
        dataSource={dataSource}
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          total,
          showTotal: (total) => `共 ${total} 条数据`,
          current: pageNum,
          pageSize,
          onChange: (page, pageSize) => {
            setState({ pageNum: page, pageSize });
            getActivationCodeData({
              pageNum: page,
              pageSize,
            });
          },
        }}
        scroll={{ x: 'max-content' }}
      />
      <Modal
        title="生成激活码"
        open={open}
        destroyOnClose
        onOk={() => {
          if (!validNum) {
            message.error('请输入有效设备数');
            return;
          }
          generateActivationCode(validNum)
            .then((res) => {
              if (res) {
                console.log(res, '生成激活码');
                message.success('激活码生成成功');
                setState({ open: false, validNum: null });
                getActivationCodeData();
              }
            })
            .catch((err) => {
              console.log(err, 'err');
            });
        }}
        onCancel={() => setState({ open: false, validNum: null })}
      >
        <Space align="end">
          <InputNumber
            min={0}
            max={1000}
            value={validNum}
            onChange={(value) => setState({ validNum: value })}
            style={{ width: '300px' }}
            placeholder="请输入该激活码可用的设备数"
          />
        </Space>
      </Modal>
    </div>
  );
};

export default ActivationCode;
